package wireless.util;
public class BinaryHexExchange {

		
		private static String hexStr =  "0123456789ABCDEF";
			
		public static void main(String[] args) 
		{
			String str = "111000001100";
			
			String hexString = BinaryToHexString(str.getBytes());
			System.out.println(str.getBytes());
			System.out.println("str转换为十六进制：\n"+hexString);
			
			System.out.println("将str的十六进制文件转换为二进制并转为String：\n"+new String(HexStringToBinary(hexString)));
		
		}
		/**
		 * 
		 * @param bytes
		 * @return 将二进制转换为十六进制字符输出
		 */
		public static String BinaryToHexString(byte[] bytes){
			
			String result = "";
			String hex = "";
			for(int i=0;i<bytes.length;i++){
				//字节高4位
				hex = String.valueOf(hexStr.charAt((bytes[i]&0xF0)>>4));
				System.out.println("hex:"+hex);
				//字节低4位
				hex += String.valueOf(hexStr.charAt(bytes[i]&0x0F));
				System.out.println("hex:"+hex);
				result +=hex;
				System.out.println("result:"+result);
			}
			return result;
		}
		/**
		 * 
		 * @param hexString
		 * @return 将十六进制转换为字节数组
		 */
		public static byte[] HexStringToBinary(String hexString){
			//hexString的长度对2取整，作为bytes的长度
			int len = hexString.length()/2;
			byte[] bytes = new byte[len];
			byte high = 0;//字节高四位
			byte low = 0;//字节低四位

			for(int i=0;i<len;i++){
				 //右移四位得到高位
				 high = (byte)((hexStr.indexOf(hexString.charAt(2*i)))<<4);
				 low = (byte)hexStr.indexOf(hexString.charAt(2*i+1));
				 bytes[i] = (byte) (high|low);//高地位做或运算
			}
			return bytes;
		}
	}